package authen;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 测试shiro认证
 *
 * @author lwh
 */
public class TestAuthenticator {

    private static Logger logger = LoggerFactory.getLogger(TestAuthenticator.class);

    public static void main(String[] args) {
        //1. 创建容器管理对象
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        //2. 给安全管理器设置Realm
        securityManager.setRealm(new IniRealm("classpath:shiro.ini"));

        //SecurityUtils：全局安全工具类
        //3. 设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);

        //4. 关键对象：Subject
        Subject subject = SecurityUtils.getSubject();

        //5. 创建认证令牌(principle, credential)
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");

        //6. 认证
        try {
            logger.info("认证前状态：" + subject.isAuthenticated());
            subject.login(token);
            logger.info("认证后状态：" + subject.isAuthenticated());
        } catch (UnknownAccountException e) {
            logger.info("认证失败：身份信息错误");
        } catch (IncorrectCredentialsException e) {
            logger.info("认证失败：凭证信息错误");
        }

        Realm realm;

    }

}
